<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class CommentController extends Controller
{
    public function index (Request $request)
    {   
        // dd($request);
    	$where = [];
    	$db = DB::table('comments');
    	
		     $db->join('goods','comments.good_id','=','goods.id')
		    	->join('users','comments.user_id','=','users.id')
		    	->select('comments.*','users.phone','users.username','goods.title')
		    	->get();

		// 判断有没有搜索name字段的值
     	//  dd();
    	if($request->has('keywords')){
    		// 获取要搜索的name字段的值
    		$name = $request->input('keywords');
    		//添加where模糊匹配条件
    		$db->where('goods.title','like',"%{$name}%");
    		$where['id'] = $name;
    	}
		    	$list = $db->paginate(5);
                // dd($list);
    	return view('admin.comment.index',['list'=>$list,'where'=>$where]);
    }

    public function destroy ($id)
    {
        // dd($id);
    	$ob = DB::table('comments')->where('pid',$id)->get();
        if(count($ob)>0){
           return redirect('admin/comment')->with('msg','要删除此评论必须先删除此评论下的回复'); 
        }

    	$row = DB::table('comments')->where('id',$id)->delete();
    	if($row>0){
    		return redirect('admin/comment')->with('msg','删除成功');
    	}
    }

    public function createSon ($id)
    {
    	// $list = DB::table('comments')->where('id',$id)->first();
    	$list = $this->xxoo($id);
    	// dd($list);
        return view('admin.comment.commentSon',['list'=>$list]);
    }



    public function xxoo($id)
    {
    	$data = DB::table('comments')
		    	->join('goods','comments.good_id','=','goods.id')
		    	->join('users','comments.user_id','=','users.id')
		    	->select('comments.content','users.username','comments.good_id as goodid','goods.title','comments.user_id as userid','comments.id','comments.star','comments.pid','comments.path')
		    	->where('comments.id',$id)->first();

		  return $data;

    }

    public function storeSon (Request $request)
    {
    	// dd($request);
        $data = $request->except('_token');

        // dd($data);
        $id = DB::table('comments')->insertGetId($data);
        if($id>0){
            return redirect('admin/comment');
        }
    }
    
}
